package com.black.utils.network.transmit.tcp;

import com.black.utils.commons.pool.PoolFactory;
import com.black.utils.commons.pool.PoolProperties;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author ylx
 */
@Slf4j
public class TCPClientFactory extends PoolFactory<TCPClient> {
    public TCPClientFactory(PoolProperties poolProperties) {
        super(poolProperties);
    }

    @Override
    public TCPClient make() {
        try {
            return new TCPClient(poolProperties);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void destroy(TCPClient tcpClient) {
        if (tcpClient.isConnected()) {
            tcpClient.close();
        }
    }

    @Override
    public boolean validate(TCPClient tcpClient) {
        return tcpClient.isAvailable() && tcpClient.isConnected();
    }

    @Override
    public void active(TCPClient tcpClient) throws Exception {
        if (!tcpClient.isConnected()) {
            tcpClient.connect();
        }
    }

    @Override
    public void passivate(TCPClient tcpClient) {
    }
}
